import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch((err) => {});
};

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
    children: [
      {
        path: "/home/searchpopup",
        component: () =>
          import(
            /* webpackChunkName: "searchpopup" */ "../views/SearchPopup.vue"
          ),
      },
    ],
    meta: {
      num: 0,
      isShowTabbar: true,
    },
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
  // tabbar专题路由
  {
    path: "/topic",
    component: () =>
      import(/* webpackChunkName: "topic" */ "../views/Topic.vue"),
    meta: {
      num: 1,
      isShowTabbar: true,
    },
  },
  // tabbar分类路由
  {
    path: "/category",
    component: () =>
      import(/* webpackChunkName: "category" */ "../views/Category.vue"),
    meta: {
      num: 2,
      isShowTabbar: true,
    },
  },
  // tabbar购物车路由
  {
    path: "/cart",
    component: () => import(/* webpackChunkName: "cart" */ "../views/Cart.vue"),
    meta: {
      num: 3,
      isShowTabbar: true,
    },
  },
  // tabbar用户路由
  {
    path: "/user",
    component: () => import(/* webpackChunkName: "user" */ "../views/User.vue"),
    meta: {
      num: 4,
      isShowTabbar: true,
    },
  },
  {
    path: "/listDetail",
    component: () =>
      import(/* webpackChunkName: "ProductionDetail" */ "../views/ProductionDetail.vue"),
    meta: {
      isShowTabbar: false,
    },
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
// 路由守卫
router.beforeEach((to, from, next) => {
  // console.log(to);
  if (to.path == "/cart") {
    // console.log("进入到购物车了");
    let token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      Vue.prototype.$toast("请先登录");
      setTimeout((item) => {
        next("/user");
      }, 800);
      return;
    }
  }
  next(); //路由放行
});

export default router;
